import { getCollection } from '@/service/collection';
import { pick } from 'lodash-es';

import { AddMenuParams, IMenu, UpdateMenuParams } from '../types/menu';

const menuCollection = getCollection<IMenu>('opendb-admin-menus');

const fields = ['menu_id', 'name', 'icon', 'url', 'sort', 'parent_id', 'permission', 'enable'];

const existMenu = async (params: { menu_id?: string; _id?: string }) => {
	const query = Object.entries(params)
		.filter(([key, value]) => value)
		.map(([key, value]) => `${key} == '${value}'`)
		.join(' || ');

	try {
		const res = await menuCollection.where(query).get();
		return res.data.length > 0;
	} catch (error) {
		throw error;
	}
};
const getAllMenu = async (query?: string) => {
	try {
		const res = await menuCollection
			.where(query || {})
			.orderBy('sort', 'asc')
			.get();
		return res;
	} catch (error) {
		throw error;
	}
};

//获取无url的menu
const getMenuWithoutUrl = async () => {
	try {
		const res = await menuCollection.where({ url: '' }).get();
		return res.data;
	} catch (error) {
		throw error;
	}
};
const getEnableMenu = async () => {
	try {
		const res = await menuCollection.where({ enable: true }).orderBy('sort', 'asc').get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const addMenu = async (data: AddMenuParams) => {
	const exist = await existMenu({ menu_id: data.menu_id });
	if (exist) {
		throw new Error('菜单标识已存在');
	}

	const omitFields = pick(data, fields);

	try {
		const res = await menuCollection.add(omitFields);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updateMenu = async (data: UpdateMenuParams) => {
	const exist = await existMenu({ _id: data._id });
	if (!exist) {
		throw new Error('菜单标识不存在');
	}

	const omitFields = pick(data, fields);

	try {
		const res = await menuCollection
			.where({
				_id: data._id,
			})
			.update(omitFields);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const switchMenuEnable = async (params: { id: string; enable: boolean }) => {
	const { id, enable } = params;
	const exist = await existMenu({ _id: id });
	if (!exist) {
		throw new Error('菜单标识不存在');
	}

	try {
		const res = await menuCollection.where({ _id: id }).update({ enable });
		return res;
	} catch (error) {
		throw error;
	}
};

const deleteMenu = async (id: string) => {
	const exist = await existMenu({ _id: id });
	if (!exist) {
		throw new Error('菜单标识不存在');
	}

	try {
		const res = await menuCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};
export const menu = {
	getAllMenu,
	getEnableMenu,
	getMenuWithoutUrl,
	addMenu,
	updateMenu,
	existMenu,
	deleteMenu,
	switchMenuEnable,
};
